package br.inf.mensageiro.main;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import br.inf.mensageiro.context.ApplicationContext;
import br.inf.mensageiro.converter.UsuarioConverter;
import br.inf.mensageiro.multicast.ServerMulticast;
import br.inf.mensageiro.pojo.Status;
import br.inf.mensageiro.pojo.Usuario;
import br.inf.mensageiro.socket.ServerSocket;
import br.inf.mensageiro.tree.TreeNodeDecision;
import br.inf.mensageiro.util.MaoUtils;
import br.inf.mensageiro.util.Parametro;
import br.inf.mensageiro.view.MainView;
import br.inf.mensageiro.view.WindowView;


public class Mensageiro {
	
	public static final Map<String,WindowView> windowViewMap=new HashMap<String,WindowView>();
	public static final Map<String,List<String>> ipwindowsViewIdMap=new HashMap<String,List<String>>();
	
	public static void main(String[] args) {		
		try{			
			String showInputDialog = (String) JOptionPane.showInputDialog(null, null, "Alias",JOptionPane.PLAIN_MESSAGE, null, null, "");
			if(showInputDialog==null || showInputDialog.length()>10){
				return;
			}
			ApplicationContext applicationContext = ApplicationContext.getInstance();
			applicationContext.setLocalHost(MaoUtils.getLocalHost());
			applicationContext.setAlias(showInputDialog);
			
			Thread chatServer=new Thread(new ServerSocket());
			chatServer.start();
			MulticastSocket multicastSoc=new MulticastSocket(Parametro.PORT_BROADCAST); 
			InetAddress group = InetAddress.getByName(Parametro.HOST_BROADCAST);
			multicastSoc.joinGroup(group);
			
			MainView mainView=new MainView("Mensageiro", multicastSoc, group);
			
			MaoUtils.registrarSystemTray(mainView, multicastSoc, group);
			JTree mainTree=mainView.getMainTree();
			DefaultTreeModel treeModel=(DefaultTreeModel)mainTree.getModel();
			DefaultMutableTreeNode top=mainView.getTop();					
			ServerMulticast.send(Status.ON_LINE);
			while(true){
				Usuario usuario;
				byte[] buf = new byte[25];
				DatagramPacket recv = new DatagramPacket(buf, buf.length);
				multicastSoc.receive(recv);
				if(applicationContext.getLocalHost().contains(recv.getAddress().getHostAddress())){
					continue;
				}
				try {
					 usuario = UsuarioConverter.converter(recv);					
				} catch (ArrayIndexOutOfBoundsException e) {
					continue;
				}				 
				TreeNodeDecision.node(mainTree, treeModel, top, usuario);
			}
			
		}catch(IOException ioe){
			ioe.printStackTrace();
		}
	}
	
}